import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Solution46 {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>(nums.length);
        for (int num : nums) {
            list.add(num);
        }
        perm(res, list, 0, nums.length - 1);
        return res;
    }

    private void perm(List<List<Integer>> res, List<Integer> nums, int start, int end) {
        if (start == end) {
            res.add(new ArrayList<>(nums));
            return;
        }
        for (int i = start; i <= end; i++) {
            Collections.swap(nums, i, start);
            perm(res, nums, start + 1, end);
            Collections.swap(nums, i, start);
        }
    }
}
